package yz.cp.back.admin.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.google.common.collect.Sets;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.common.utils.Base64DecodeMultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/web/upload")
public class UploadController {
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @SneakyThrows
    @RequestMapping(value = "/file",method = RequestMethod.POST)
    public ApiResult upload(@RequestParam(required = false) MultipartFile file,
                            @RequestParam(required = false) String base64,
                            HttpServletRequest request) {

        if(StringUtils.isNotBlank(base64)){
            file= Base64DecodeMultipartFile.base64Convert(base64);
        }
        String ext=org.springframework.util.StringUtils.getFilenameExtension(file.getOriginalFilename());
        FastFile fastFile=new FastFile(file.getInputStream(),file.getSize(),ext, Sets.newLinkedHashSet());
        StorePath storePath=storageClient.uploadFile(fastFile);
        String fullPath=fdfsWebServer.getWebServerUrl()+storePath.getGroup()+"/"+storePath.getPath();
        return ApiResult.Custom().success().put("fullPath",fullPath);
    }
}

